Reducing shader switches

Kanzi must switch shaders every time when rendered batch has a different shader compared to the previous batch. Because materials can have their own vertex and fragment shaders, in some cases your application has to switch shaders several times during the rendering of a scene.

In OpenGL vertex and fragment shaders are each compiled into a shader program and are sent to the GPU whenever it needs to be used. The GPU only stores one program at a time. At least one shader switch must be made for each material in a scene. If objects are presented in an order that requires excessive switching between shader programs, the rendering can slow down.

You can see the number of shader switches in the Kanzi Studio Preview Performance HUD, or in the Kanzi Engine API by calling getShaderSwitchCount(). See Measuring the performance of your application.

Shader switching decreases the performance of your application, so keep shader switching to a minimum. To reduce shader switches:

Rendering nodes by material type

Even though you can increase performance by rendering nodes by material type, sorting batches by shader can be much more efficient, because sorting by batches takes the sub-materials into account. See Sorting batches by shader in render passes.

Note that this operation increases the use of the CPU.

To render nodes by the material type:

  1. In the Library press Alt and right-click Composing > Pipeline and select Sorting Filter.
  2. In the Properties set:
  3. To take the filter into use, in the Library > Composing create a Render Pass or a Composer and a Render Pass, that you want to use to render your scene.
  4. In the Library select the Render Pass and in the Properties set the Object Source property to the filter you created.
  5. In the Project select the Scene node to which you want to apply the filter and in the Properties set the Composer property to the composer or render pass that uses as its object source the filter you created.
    Kanzi Studio renders the nodes collected by the filter.

Sorting batches by shader in render passes

Note that this operation increases the use of the CPU.

To sort batches by shader in render passes:

  1. In the Library select Composing > Composers and in the composer select the render pass you want to set.
  2. In the Properties enable the Sort Batches by Shader property.

See also

Using binary shaders

Optimizing fragment shaders

Loading resources in parallel

Shaders best practices

Measuring the performance of your application

Best practices